<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Action</title>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/vuex@next"></script>
</head>
<body>

    <div id="app">
        <div v-for="( s , i ) in list" :key="s.id">
            {{i+1}} , {{s.id}} , {{s.name}} , {{s.gender}} , 
            <a href="#" @click.stop.prevent="edit({id:s.id,property:'name',value:'开发喵'})">编辑</a>
            <a href="#" @click.stop.prevent="del(s.id)">删除</a>
        </div>
    </div>

    <script>
        const store = Vuex.createStore({
            state:{
                students: [
                    { id: 1001 , name: '朱亚红' , gender: '女' },
                    { id: 1002 , name: '马飞燕' , gender: '女' },
                    { id: 2003 , name: '郑娅婷' , gender: '女' },
                    { id: 3004 , name: '马俊珍' , gender: '女' }
                ]
            },
            getters: {
                list: state => state.students
            },
            mutations: {
                remove(state,id){
                    console.log( 'remove: ' , id );
                    let index = state.students.findIndex( s => s.id == id );
                    if( index != -1 ) {
                        state.students.splice( index , 1 );
                    }
                },
                update(state,payload){
                    console.log( 'update: ' , payload );
                    let stu = state.students.find( s => s.id == payload.id );
                    if( stu ) {
                        stu[ payload.property ] = payload.value ;
                    }
                }
            },
            actions: {
                remove(context,id) {
                    console.log( 'action remove: ' , id );
                    // 通过 context 提交 mutation 并为其指定 payload
                    context.commit( 'remove' , id );
                },
                update(context,payload) {
                    setTimeout( ()=>{
                        context.commit( 'update' , payload );
                    }, 1000 );
                    
                }
            }
        });

        const app = Vue.createApp({
            data(){ 
                return { title: '学生列表' } 
            },
            methods: {
                ...Vuex.mapActions( { del : 'remove' , edit: 'update' } )
            },
            computed: {
                ...Vuex.mapGetters( [ 'list' ] )
            }
        });

        app.use( store );

        app.mount( "#app" );
    </script>
    
</body>
</html>